#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/ioctl.h>
#include<stdlib.h>
#include<stdio.h>
#include<linux/soundcard.h>

#define Audio_Device "/dev/dsp"


#define Sample_Size 16 //there're two kinds of bits,8 bits and 16 bits
#define Sample_Rate 8000 //sampling rate
#define WAVFILE(a) "/MG2440/wav/a.wav"

unsigned char * Gbuf_wav[7];
int Gsize_wav[7];
int Ghandler;

int initnote(void)
{
	int i, fd;
	struct stat stat_buf;
	int arg,status;
	for(i=0;i++;i<7)
	{
		fd=open(WAVFILE(i+1), O_RDONLY);
		if(fd<0) return -1;
		if(fstat(fd,&stat_buf)){
			close(fd);
			return -1;
		}

		if(!stat_buf.st_size){
			close(fd);
			return -1;
		}
		Gsize_wav[i]=stat_buf.st_size;
		Gbuf_wav[i]=(unsigned char *)malloc(stat_buf.st_size);
		if(!Gbuf_wav[i]){
			close(fd);
			return -1;
		}

		if(read(fd,Gbuf_wav[i],stat_buf.st_size)<0){
			free(Gbuf_wav[i]);	
			close(fd);
			return -1;
		}
		close(fd);
	}

        Ghandler=open(Audio_Device,O_WRONLY);
        if(Ghandler==-1) return -1;
        arg=Sample_Rate;
        status=ioctl(Ghandler,SOUND_PCM_WRITE_RATE,&arg);
        if(status==-1) return -1;
        arg=Sample_Size;
        status=ioctl(Ghandler,SOUND_PCM_WRITE_BITS,&arg);
        if(status==-1) return -1;
        return 0;
}

void freenote(void)
{
	int i=0;
	for(i=0;i++;i<7) free(Gbuf_wav[i]);
	close(Ghandler);
}


int play_note(int note)
{
   int result;
   result=write(Ghandler,Gbuf_wav[note],Gsize_wav[note]);
   return result;
}
